package cn.xchats.rpc.server;

import cn.xchats.rpc.common.annotation.RpcReference;
import cn.xchats.rpc.common.annotation.RpcService;
import cn.xchats.rpc.common.core.CacheBeanMethod;
import cn.xchats.rpc.common.core.Invoke;
import cn.xchats.rpc.common.core.ZookeeperService;
import cn.xchats.rpc.common.dto.BeanMethod;
import cn.xchats.rpc.common.type.ZookeeperNodeType;
import cn.xchats.rpc.common.util.PropertyUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Set;

/*
 * 中介服务
 * 每个bean实例化的时候 都会执行当前class
 *@author teddy
 *@date 2018/7/3
 */
@Component
public class ServerMediator implements BeanPostProcessor, CommandLineRunner {

    @Autowired
    private ZookeeperService zookeeperService;

    private boolean registerInitNode = false;

    @Override
    public void run(String... args) throws Exception {
        //注册初始节点
        //registerInitNode();
    }


    public ServerMediator() {
    }


    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * 初始化完bean之后执行该方法
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean.getClass().isAnnotationPresent(RpcService.class)) {
            Map<String, BeanMethod> beanMethodMap = Invoke.generateInterfaceInfo(bean);
            CacheBeanMethod.beanMap.putAll(beanMethodMap);
            registerService(beanMethodMap);
        }

        return bean;
    }

    private void registerService(Map<String, BeanMethod> beanMethodMap) {
        if (!registerInitNode) {
            registerInitNode();
            registerInitNode = true;
        }
        Set<String> methodKeySet = beanMethodMap.keySet();
        for (String methodKey : methodKeySet)
            //zookeeperService.createEphemeralEmptyNode(ZookeeperNodeType.SERVER_TYPE + "/" + ZookeeperNodeType.hostAddress + "/" + methodKey);
            zookeeperService.createEphemeralNode(ZookeeperNodeType.SERVER_TYPE + "/" + ZookeeperNodeType.hostAddress + "/" + methodKey, methodKey);
    }

    /**
     * 服务注册
     */
    private void registerInitNode() {
        String hostAddress = null;
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
            ZookeeperNodeType.hostAddress = hostAddress+":"+Integer.valueOf(PropertyUtil.getProperty("tcp.server.port"));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        //主节点是否存在
        if (!zookeeperService.checkNodePath(ZookeeperNodeType.SERVER_TYPE))
            zookeeperService.createEmptyNode(ZookeeperNodeType.SERVER_TYPE);

        //临时存在说明 client端宕机之后 zookeeper的服务端心跳还没来得及开始检测 所以节点没删除（可以在zookeeper里设置心跳间隔  或者在这判断一下）
        //if (zookeeperService.checkNodePath(ZookeeperNodeType.SERVER_TYPE + "/" + hostAddress))
        //    zookeeperService.deleteNode(ZookeeperNodeType.SERVER_TYPE + "/" + hostAddress);
        if (!zookeeperService.checkNodePath(ZookeeperNodeType.SERVER_TYPE + "/" + ZookeeperNodeType.hostAddress))
            zookeeperService.createEmptyNode(ZookeeperNodeType.SERVER_TYPE + "/" + ZookeeperNodeType.hostAddress);

        System.out.println("服务已完成注册");
    }
}
